package com.rockbb.common.utilities.i18n;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import com.rockbb.common.simpleframe.config.SimpleConfig;

public class MessageResourceFactory {

	private static final int defaultLangId = Integer.parseInt(SimpleConfig.getConfig("default_language"));

	private static final Map<Integer, MessageResource> msgResourceMap = initialize();

	private static Map<Integer, MessageResource> initialize() 
	{
		// 根据 interface languages 初始化语系档
		List<Language> languages = SimpleConfig.getLanguages();

		Map<Integer, MessageResource> map = new HashMap<Integer, MessageResource>();
		for (int i=0; i<languages.size(); i++) 
		{
			Locale locale = languages.get(i).getLocale();
			String a = SimpleConfig.getConfig("languages_path");
			ResourceBundle rb = ResourceBundle.getBundle(SimpleConfig.getConfig("languages_path"), locale);
			MessageResource msgRes = new MessageResource(rb);
			map.put(i, msgRes);
		}
		return map;
	}

	public static Integer[] getLangIds() 
	{
		return msgResourceMap.keySet().toArray(new Integer[0]);
	}

	/**
	 * 根据lang和country信息, 选中当前语系列表中最匹配的语系档
	 * 
	 * @param lang
	 * @param country
	 * @return
	 */
	public static int getLangId(String lang, String country) 
	{
		if (lang!= null) 
		{
			int langId = 0;
			List<Language> languages = SimpleConfig.getLanguages();
			for (int i=0; i<languages.size(); i++) 
			{
				if (lang.equals(languages.get(i).getName())) 
				{
					langId = i;
					if (country.equals(languages.get(i).getCountry()))
					{
						return langId;
					}
				}
			}
			return langId;
		}
		else
		{
			return defaultLangId;
		}
	}

	public static MessageResource getMessageResource(int langId) 
	{
		MessageResource msgResObj = msgResourceMap.get(langId);
		if (msgResObj == null) 
		{
			return msgResourceMap.get(defaultLangId);
		}
		else 
		{
			return msgResObj;
		}
	}

	public static MessageResource getRawMessageResource(int langId) 
	{
		return msgResourceMap.get(langId);
	}
}
